package com.aek.aekdroid;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Application;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.preference.PreferenceManager;

import com.aek.aekdroid.data.Match;
import com.aek.aekdroid.data.MatchData;

public class AekDroidApplication extends Application implements OnSharedPreferenceChangeListener {
	public static final String TAG = "AekDroidApplication";
	private SharedPreferences prefs;
	private MatchData matchData;
	private WebAekDroid webAekdDroid = null;
	private Long interval;
	private boolean vibrate;
	public static String newVersion = "";

	@Override
	public void onCreate() {
		super.onCreate();
		setUpPrefs();
		this.interval = getInterval();
		this.matchData = new MatchData(this);
		MyLog.i(TAG, "onCreated");
	}

	private void setUpPrefs() {
		this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
		this.prefs.registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
		MyLog.i(TAG, "onTerminate");
	}

	public SharedPreferences getPrefs() {
		if (prefs == null) {
			MyLog.d(TAG, "Prefs is null.Setting new one");
			setUpPrefs();
		}
		return this.prefs;
	}

	public WebAekDroid getWebAekDroid() {
		if (this.webAekdDroid == null) {
			MyLog.d(TAG, "Connect to domain:" + WebAekDroid.DOMAIN);
			this.webAekdDroid = new WebAekDroid(this, WebAekDroid.DOMAIN);
		}
		return this.webAekdDroid;
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences prefs, String str) {
		this.webAekdDroid = null;
		this.prefs = null;
		this.matchData = new MatchData(this);
	}

	public MatchData getMatchData() {
		return matchData;
	}

	public synchronized int fetchUpdates() {
		MyLog.d(TAG, "Fetching Updates");
		List<Match> matches = new ArrayList<Match>();
		int updates = 0;
		try {
			long lastTimeUpdated = matchData.getLastTimeUpdated() / 1000;
			MyLog.d(TAG, "lastTimeUpdated : " + lastTimeUpdated);
			matches = webAekdDroid.getMatches(lastTimeUpdated, getPeriod());
			ContentValues values = new ContentValues();
			if (matches != null) {
				for (Match match : matches) {
					MyLog.d(TAG, "Match Update in web db:" + match.updated);
					if (match.id > 0) {
						// Update match table
						values.put(MatchData.MATCHES_C_ID, match.id);
						values.put(MatchData.MATCHES_C_AWAY_GOALS, match.awaygoals);
						values.put(MatchData.MATCHES_C_AWAY_TEAM, match.awayteam);
						values.put(MatchData.MATCHES_C_CHANNEL, match.channel);
						values.put(MatchData.MATCHES_C_DATETIME, match.datetime);
						values.put(MatchData.MATCHES_C_PERIOD, match.period);
						values.put(MatchData.MATCHES_C_HOME_GOALS, match.homegoals);
						values.put(MatchData.MATCHES_C_HOME_TEAM, match.hometeam);
						values.put(MatchData.MATCHES_C_STADIUM, match.stadium);
						values.put(MatchData.MATCHES_C_TOURNAMENT, match.tournament);
						values.put(MatchData.MATCHES_C_UPDATED, match.updated);
						values.put(MatchData.MATCHES_C_DELETED, match.deleted);
						values.put(MatchData.MATCHES_C_PLAYERS, match.players);
						this.matchData.insertOrUpdate(values, match.details);
						updates++;
					}
				}
			} else {
				MyLog.e(TAG, "Could not connect to the site");
				return -1;
			}
		} catch (IOException e) {
			MyLog.e(TAG, "Could not read from the url");
			e.printStackTrace();
			return -1;
		}
		MyLog.d(TAG, "There were " + updates + " updates");
		return updates;

	}

	/**
	 * @param interval
	 *            the interval to set
	 */
	public void setInterval(Long interval) {
		this.interval = interval;
	}

	/**
	 * @return the interval
	 */
	public Long getInterval() {
		return Helper.getLongPref(this.getPrefs(), getString(R.string.pref_updateFreqKey), 0L);
	}

	public boolean isVibrate() {
		return this.getPrefs().getBoolean(getString(R.string.pref_vibrateKey), false);
	}

	public boolean isCheckUpdate() {
		return this.getPrefs().getBoolean(getString(R.string.pref_updateKey), false);
	}

	public String getPeriod() {
		return getPrefs().getString(getString(R.string.pref_periodKey), Helper.getDefaultPeriod());
	}

	public String getPassword() {
		return getPrefs().getString(getString(R.string.pref_adminKey), "");
	}

	public boolean isAdmin() {
		return new File(this.getFilesDir().getAbsolutePath() + "/admin").isFile();
	}

	public String getLatestVersion(String strNewVersion) {
		String strCurrVersion = getString(R.string.app_version);
		String[] tokens = strCurrVersion.split(" ");
		try {
			double currVersion = Double.parseDouble(tokens[0]);
			// String strNewVersion = webAekdDroid.getNewVersion();
			double newVersion = Double.parseDouble(strNewVersion);
			if (currVersion < newVersion) {
				return String.valueOf(newVersion);
			} else {
				return null;
			}
		} catch (NumberFormatException ex) {
			return null;
		}
		// } catch (IOException ex) {
		// return null;
		// }
	}

	public boolean isAddToCalendar() {
		return this.getPrefs().getBoolean(getString(R.string.pref_calendarKey), false);
	}

	public String getCalendarBase() {
		if (getPrefs().contains(getString(R.string.pref_calendarBaseKey))) {
			return getPrefs().getString(getString(R.string.pref_calendarBaseKey), null);
		}
		return null;
	}

	public void setCalendarBase(String base) {
		SharedPreferences.Editor editor = getPrefs().edit();
		editor.putString(getString(R.string.pref_calendarBaseKey), base);
		editor.commit();

	}

	public void setSelectedCalendarId(String id) {
		MyLog.d(TAG, "Inserting calendar Id " + id);
		SharedPreferences.Editor editor = getPrefs().edit();
		editor.putString(getString(R.string.pref_calendarIdKey), id);
		editor.commit();

	}

	public String getSelectedCalendarId() {
		if (getPrefs().contains(getString(R.string.pref_calendarIdKey))) {
			return getPrefs().getString(getString(R.string.pref_calendarIdKey), null);
		}
		return null;
	}

	public int getVersion() {
		try {
			PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
			MyLog.d(TAG, "Version: " + info.versionCode);
			return info.versionCode;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}
}
